package com.sneakxy.mybatis.commons.repository.query.domain;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * @author 潜行的青衣
 */
public class CriteriaImpl<T> implements Criteria<T> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3905851275520295618L;
	
	private List<Condition> conditions = new ArrayList<Condition>();
	
	public CriteriaImpl(List<String> opts, List<Criterion> criterions) {
		this.init(opts, criterions);
	}
	
	public CriteriaImpl(List<Condition> conditions) {
		this.conditions = conditions;
	}

	/* (non-Javadoc)
	 * @see java.lang.Iterable#iterator()
	 */
	@Override
	public Iterator<Condition> iterator() {
		return conditions.iterator();
	}

	private void init(List<String> opts, List<Criterion> criterions) {
		if(opts != null && criterions != null) {
			Iterator<String> oit = opts.iterator();
			Iterator<Criterion> cit = criterions.iterator();
			while(oit.hasNext()) {
				conditions.add(new Condition(oit.next(), cit.next()));
			}
		}
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(this.conditions).toHashCode();
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj) {
		if(obj == null) {
			return false;
		}
		if(!(obj instanceof CriteriaImpl)) {
			return false;
		}
		CriteriaImpl<T> criteria = (CriteriaImpl<T>) obj;
		return new EqualsBuilder().append(this.conditions, criteria.conditions).isEquals();
	}

}
